package router

import (
	"github.com/gin-gonic/gin"
	"google.golang.org/grpc"
	"google.golang.org/grpc/resolver"
	"log"
	"net"
	"project-common/discovery"
	"project-common/logs"
	loginservicev1 "project-grpc/user/login"
	"project-user/config"
	"project-user/internal/interceptor"
	login "project-user/pkg/service/login.service.v1"
)

// Router 接口
type Router interface {
	Route(r *gin.Engine)
}

type RegisterRouter struct {
}

func New() *RegisterRouter {
	return &RegisterRouter{}
}

func (*RegisterRouter) doRegister(ro Router, r *gin.Engine) {
	ro.Route(r)
}

var routers []Router

func InitRouter(r *gin.Engine) {
	//rg := New()
	//rg.doRegister(&login.RouterUser{}, r)
	for _, ro := range routers { //遍历每个实现了route接口的具体实现类,执行其中的Route方法
		ro.Route(r)
	}
}

func AddRouter(ro ...Router) {
	routers = append(routers, ro...)
}

//---------------------------------------------------------

type gRPCConfig struct {
	Addr         string
	RegisterFunc func(*grpc.Server)
}

// RegisterGrpc 本服务作为grpc服务启动
func RegisterGrpc() *grpc.Server {
	c := gRPCConfig{
		Addr: config.C.GC.Addr,
		RegisterFunc: func(g *grpc.Server) { //g:服务    参2: 创建LoginService结构体
			loginservicev1.RegisterLoginServiceServer(g, login.New()) //这里的注册方法, 是grpc.pb文件中的   g:*grpc.Server  参2:自定义的loginServer的New()方法
		}}

	//s := grpc.NewServer(grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(
	//	//otelgrpc.UnaryServerInterceptor(),
	//	grpc.UnaryInterceptor(),
	//	interceptor.New(),
	//)))

	//创建服务   参数:添加拦截器
	s := grpc.NewServer(interceptor.New().Cache())
	c.RegisterFunc(s)

	lis, err := net.Listen("tcp", c.Addr)
	if err != nil {
		log.Println("cannot listen")
	}

	go func() {
		err = s.Serve(lis)
		if err != nil {
			log.Println("server started error", err)
			return
		}
	}()

	return s
}

func RegisterEtcdServer() {

	etcdRegister := discovery.NewResolver(config.C.EtcdConfig.Addrs, logs.LG) //根据etcd地址, 创建一个自定义的注册器, 该注册器实现了grpc.resolver类的所有方法
	resolver.Register(etcdRegister)                                           //

	info := discovery.Server{ //创建一个server对象
		Name:    config.C.GC.Name,
		Addr:    config.C.GC.Addr,
		Version: config.C.GC.Version,
		Weight:  config.C.GC.Weight,
	}

	r := discovery.NewRegister(config.C.EtcdConfig.Addrs, logs.LG) //根据etcd地址, 创建注册器
	_, err := r.Register(info, 2)                                  //注册器在etcd中, 根据信息创建服务节点
	if err != nil {
		log.Fatalln(err)
	}
}
